// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env:cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

var $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.action) {
    case 'total': {
      return total(event)
    }
    case 'shoucang': {
      return shoucang(event)
    }
    default: {
      return
    }
}


async function shoucang(event){
  const result = await db.collection('gxts')
    .aggregate()
    .lookup({
      from: 'collect',
      localField: '_id',
      foreignField: 'collectId',
      as: 'categories'
    })
    .replaceRoot({
      newRoot: $.mergeObjects([ $.arrayElemAt(['$categories', 0]), '$$ROOT' ])
    })
    .project({
      categories: 0
    })
    .end()
    // .orderBy('createTime', 'asc')
    // .get()
    console.log(result)
    return result.list
}

async function total(event) {
  const countResult = await db.collection('biaobai').count()
  const total1 = countResult.total
  const xianzhiResult = await db.collection('xianzhi').count()
  const total2 = xianzhiResult.total

  const gxtsResult = await db.collection('gxts').count()
  const total3 = gxtsResult.total

  const lostResult = await db.collection('lost').count()
  const total4 = lostResult.total
  let list=[]
  list.push(
    {
      value: total1,
      name: '表白'
    },
    {
      value: total2,
      name: '闲置'
    },
    {
      value: total3,
      name: '共享资源'
    },
    {
      value: total4,
      name: '失物招领'
    }

  )
  return list
}
}
